﻿using Lib.Configuration.Entitys;
using Lib.ConfigurationBase;
using Microsoft.Extensions.Configuration;
using System.Reflection;

namespace Lib.Configuration;

/// <summary>
/// 
/// </summary>
[Serializable]
public static class Configs  {
    /// <summary>
    /// 静态构造函数
    /// </summary>
    static Configs() {
        //
        EntityKeys = [.. Assembly.GetExecutingAssembly().GetTypes().Where(T => T.Namespace == "Lib.Configuration.Entitys").Select(T => T.FullName)];
        //
        Initialize(); 
        //
        InitConfigurationRoot();
    }
    /// <summary>
    /// 
    /// </summary>
    private static List<string> EntityKeys { get; set; }
    /// <summary>
    /// AppSettings 配置文件对象
    /// </summary>
    public static IConfigurationRoot ConfigurationRoot { get; set; }
    /// <summary>
    /// 初始化默认值
    /// </summary>
    public static void Initialize() {
        if (!ApplicationType.HasValue) {
            ApplicationType = 0;
        }
        if (string.IsNullOrEmpty(ProjectDirectory)) {
            ProjectDirectory = Directory.GetCurrentDirectory();
        }
        if (string.IsNullOrEmpty(RootDirectory)) {
            RootDirectory = "Web";
        }
        if (string.IsNullOrEmpty(ConfigDirectory)) {
            ConfigDirectory = "Configs";
        }
        if (string.IsNullOrEmpty(FontDirectory)) {
            FontDirectory = "Fonts";
        }
        if (string.IsNullOrEmpty(TemplateDirectory)) {
            TemplateDirectory = "Templates";
        }
        if (string.IsNullOrEmpty(ProviderDirectory)) {
            ProviderDirectory = "Providers";
        }
    }
    /// <summary>
    /// 读取“AppSettings”配置文件
    /// </summary>
    /// <param name="Action"></param>
    /// <returns></returns>
    internal static IConfigurationRoot InitConfigurationRoot() {
        try {
            return ConfigsBase.InitConfigurationRoot("AppSettings", null, (Root, File, SubKey, Reload) => {
                //
                Configs.ConfigurationRoot = Root;
                //
                if (!Reload) {
                    //
                    var Type = typeof(Configs);
                    //
                    foreach (PropertyInfo P in Type.GetProperties(BindingFlags.Static | BindingFlags.Public)) {
                        if (P.Name.LastIndexOf("Directory") > -1 && P.PropertyType.Name == "String") {
                            var BaseDirectory = P.Name switch {
                                "ConfigDirectory" => AppDomain.CurrentDomain.BaseDirectory.TrimStart('\\'),
                                "ProjectDirectory" => null,
                                _ => Configs.ProjectDirectory,
                            };
                            P.SetValue(null, ParseDirectory(Root.GetValue(P.PropertyType, P.Name)?.ToString(), BaseDirectory, P.GetValue(null)?.ToString()));
                        } else {
                            switch (P.Name) {
                                case "ConfigurationRoot":
                                    break;
                                default:
                                    if (P.PropertyType.IsClass && P.PropertyType.Name != "String" && EntityKeys.Contains(P.PropertyType.FullName)) {
                                        P.SetValue(null, ConfigsBase.Initialize(P.PropertyType, Activator.CreateInstance(P.PropertyType), $"@{P.Name}"));
                                    } else {
                                        P.SetValue(null, Root.GetValue(P.PropertyType, P.Name));
                                    }
                                    break;
                            }
                        }
                    }
                }
                Console.WriteLine($"\n{DateTime.Now:yyyy-MM-dd HH:mm:ss} 配置文件“AppSettings.json”已{(Reload ? "重载" : "加载")}成功!\n");
            });
        } catch (Exception Ex) {
            Console.WriteLine("错误信息：" + Ex.Message);
            Console.WriteLine("异常对象：" + Ex.Source);
            Console.WriteLine("调用堆栈：" + Ex.StackTrace);
            Console.WriteLine("触发类名：" + Ex.TargetSite?.DeclaringType?.FullName);
            Console.WriteLine("触发方法：" + Ex.TargetSite?.Name);
        }
        return null;
    }
    /// <summary>
    /// 解析路径，以“网站根目录”为根目录
    /// </summary>
    /// <param name="Path">虚拟路径</param>
    /// <returns>返回物理路径</returns>
    public static string Parse(string Path) {
        if (string.IsNullOrEmpty(Path)) {
            return Path;
        }
        Path = Path.Replace(@"\", "/");
        if (Path.Contains(":/")) {
            return Path;
        }
        return $"{Configs.RootDirectory}{Path.TrimStart('/')}";
    }
    /// <summary>
    /// 解析目录（结尾包含“/”）
    /// </summary>
    /// <param name="Path"></param>
    /// <param name="BaseDirectory"></param>
    /// <param name="DefaultDirectory"></param>
    /// <returns></returns>
    public static string ParseDirectory(string Path, string BaseDirectory, string DefaultDirectory = null) {
        if (!string.IsNullOrEmpty(BaseDirectory)) {
            BaseDirectory = BaseDirectory.Replace(@"\", "/");
        }
        if (!string.IsNullOrEmpty(DefaultDirectory)) {
            DefaultDirectory = DefaultDirectory.Replace(@"\", "/");
        }
        if (string.IsNullOrEmpty(Path)) {
            if (string.IsNullOrEmpty(DefaultDirectory)) {
                if (string.IsNullOrEmpty(BaseDirectory)) {
                    Path = null;
                } else {
                    Path = $@"{BaseDirectory.TrimEnd('/')}/";
                }
            } else {
                if (DefaultDirectory.Contains(":/")) {
                    Path = $@"{DefaultDirectory.TrimEnd('/')}/";
                } else {
                    if (string.IsNullOrEmpty(BaseDirectory)) {
                        Path = $@"{DefaultDirectory.TrimStart('/').TrimEnd('/')}/";
                    } else {
                        Path = $@"{BaseDirectory.TrimEnd('/')}/{DefaultDirectory.TrimStart('/').TrimEnd('/')}/";
                    }
                }
            }
        } else {
            Path = Path.Replace(@"\", "/");
            if (Path.Contains(":/")) {
                Path = $@"{Path.TrimEnd('/')}/";
            } else {
                if (string.IsNullOrEmpty(BaseDirectory)) {
                    Path = $@"{Path.TrimStart('/').TrimEnd('/')}/";
                } else {
                    Path = $@"{BaseDirectory.TrimEnd('/')}/{Path.TrimStart('/').TrimEnd('/')}/";
                }
            }
        }
        return Path;
    }

    /// <summary>
    /// 获取 AppSettings 配置文件指定节点 Key 配置值
    /// </summary>
    public static T Get<T>(string Key, T DefaultValue = default) {
        try {
            //
            return ConfigurationRoot.GetValue(Key, DefaultValue);
            //
        } catch (Exception) {

        }
        return DefaultValue;
    }


    /// <summary>
    /// 网站根目录（物理路径：配置时“E:\WebSite\Web”或“E:/WebSite/Web”或“Web”，输出时物理路径格式“E:/WebSite/Web/”结尾包含“/”）
    /// </summary>
    public static string RootDirectory { get; internal set; }
    /// <summary>
    /// 工作目录（物理路径：配置时“E:\WebSite”或“E:/WebSite”，输出时物理路径格式“E:/WebSite/”结尾包含“/”）
    /// </summary>
    public static string ProjectDirectory { get; internal set; }
    /// <summary>
    /// 配置文件存放目录（物理路径：配置时“E:\Configs\”或“E:/Configs”或“Configs”，输出时物理路径格式“E:/Configs/”结尾包含“/”）
    /// </summary>
    public static string ConfigDirectory { get; internal set; }
    /// <summary>
    /// 配置字体文件存放目录（物理路径：配置时“E:\Fonts”或“E:/Fonts”或“ Fonts”，输出时物理路径格式“E:/Fonts/”结尾包含“/”）
    /// </summary>
    public static string FontDirectory { get; internal set; }
    /// <summary>
    /// 配置模板文件存放目录（物理路径：配置时“E:\Templates”或“E:/Templates”或“ Templates”，输出时物理路径格式“E:/Templates/”结尾包含“/”）
    /// </summary>
    public static string TemplateDirectory { get; internal set; }
    /// <summary>
    /// 配置数据库连接提供程序集文件存放目录（物理路径：配置时“E:\Providers”或“E:/Providers”或“ Providers”，输出时物理路径格式“E:/Providers/”结尾包含“/”）
    /// </summary>
    public static string ProviderDirectory { get; internal set; }


    /// <summary>
    /// 系统版本号
    /// </summary>
    public static string Version { get; set; }
    /// <summary>
    /// 当前应用程序类型, 0.Web 1.MVC 2.API 3.Console 5.WFP 6.WinForm
    /// </summary>
    public static int? ApplicationType { get; set; }
    /// <summary>
    /// 是否启用开发调试模式
    /// </summary>
    public static bool IsDevelopment { get; set; }
    /// <summary>
    /// 平台机构主键
    /// </summary>
    public static int? OrganizeID { get; set; }
    /// <summary>
    /// 默认数据库连接名称
    /// </summary>
    public static string ConnectKey { get; set; }
    /// <summary>
    /// 分布式缓存连接名称（Redis 数据库）
    /// </summary>
    public static string SessionKey { get; set; }
    /// <summary>
    /// 分布式加密解密密钥
    /// </summary>
    public static string MachineKey { get; set; }



    /// <summary>
    /// 上传配置
    /// </summary>
    public static Entitys.File File { get; internal set; }
    /// <summary>
    /// 缩略图配置
    /// </summary>
    public static Thumb Thumb { get; internal set; }
    /// <summary>
    /// 水印配置
    /// </summary>
    public static Picture Picture { get; internal set; }
    /// <summary>
    /// 网站信息配置
    /// </summary>
    public static Site Site { get; internal set; }
    /// <summary>
    /// 网站参数配置
    /// </summary>
    public static Option Option { get; internal set; }
    /// <summary>
    /// 用户配置
    /// </summary>
    public static User User { get; internal set; }


}

